<script lang="ts" setup>
  import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
  import * as echarts from 'echarts/core';
  const props = defineProps({
    dataBar1: { type: Object as () => any, required: true },
    dataBar2: { type: Object as () => any, default: [] },
    dataBar3: { type: Object as () => any, default: [] },
    dataBar4: { type: Object as () => any, default: [] },
    dataLine1: { type: Object as () => any, default: [] },
    dataLine2: { type: Object as () => any, default: [] },
    datax: { type: Object as () => any, required: true },
    yAxisName: { type: Object as () => any, default: [] },
    barName: { type: Object as () => any, default: [] },
    lineName: { type: Object as () => any, default: [] },
    formatVal: { type: Object as () => any, default: [] },
    title: { type: String, default: '' },
    legendPos: { type: Number, default: 5 },
  });

  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;

  const option = ref<any>({
    title: {
      text: props.title, // 图表标题
      left: 'center', // 标题居中
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
      },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { 
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      },
      backgroundColor: 'rgba(0,24,48,0.95)',
      borderColor: '#00f6ff',
      borderWidth: 2,
      textStyle: { 
        color: '#fff',
        fontSize: 14
      },
      padding: [8, 12],
      appendToBody: true,
      position: function (point: any) {
        return [point[0], point[1] + 20];
      },
      formatter: function (params: any[]) {
        if (!params || params.length === 0) return '';
        let html = `<div style="font-weight:600;color:#00f6ff;margin-bottom:6px;border-bottom:1px solid rgba(0,246,255,0.3);padding-bottom:4px;">${params[0].name}</div>`;
        params.forEach((item) => {
          let value = item.value;
          let color = item.color;
          if (props.formatVal.length > 0 && props.formatVal.includes(item.seriesName)) {
            value = value.toFixed(2) + '%';
          } else {
            color = item.color.colorStops ? item.color.colorStops[0].color : item.color;
          }
          html += `
            <div style="display: flex; align-items: center; margin-top: 6px;line-height:20px;">
              <span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background-color: ${color}; margin-right: 8px;"></span>
              <span style="color:#b2eaff;">${item.seriesName}:</span>
              <span style="color:#fff;font-weight:600;margin-left:8px;">${value}</span>
            </div>
          `;
        });
        return html;
      },
    },
    legend: {
      data: [...props.barName, ...props.lineName],
      top: '0%',
      textStyle: { 
        color: '#FFFFFF', 
        fontSize: 12,
      },
      right: props.legendPos,
      itemWidth: 16,
      itemHeight: 10,
      itemGap: 50,
      selectedMode: false,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '0%',
      containLabel: true, // 让 grid 包含坐标轴文本
    },
    xAxis: {
      type: 'category',
      data: props.datax ?? [],
      axisLabel: {
        show: true,
        color: '#b2eaff',
        fontSize: 11,
        fontWeight: 'bold',
        textShadow: '0 0 6px rgba(0,246,255,0.6)',
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(78,207,255,0.6)',
          width: 2,
        },
      },
      axisTick: {
        show: false,
      },
    },
    yAxis: [
      {
        type: 'value',
        name: props.yAxisName[0],
        nameTextStyle: {
          color: '#b2eaff',
          fontSize: 12,
          fontWeight: 'bold',
        },
        axisLabel: {
          formatter: '{value}',
          color: '#b2eaff',
          fontSize: 11,
          textShadow: '0 0 6px rgba(0,246,255,0.6)',
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: 'rgba(78,207,255,0.6)',
            width: 2,
          },
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            color: 'rgba(78,207,255,0.15)',
            width: 1,
          },
        },
      },
      {
        type: 'value',
        name: props.yAxisName[1],
        scale: true,
        position: 'right',
        nameTextStyle: {
          color: '#b2eaff',
          fontSize: 12,
          fontWeight: 'bold',
        },
        axisLabel: {
          formatter: '{value}',
          color: '#b2eaff',
          fontSize: 11,
          textShadow: '0 0 6px rgba(0,246,255,0.6)',
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: 'rgba(78,207,255,0.6)',
            width: 2,
          },
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: false,
        },
      },
    ],
    series: [
      // 第一个柱状图的钻石顶部（功率实际值）
      {
        z: 2,
        name: props.barName[0] ?? '',
        type: 'pictorialBar',
        symbolPosition: 'end',
        data: props.dataBar1 ?? [],
        symbol: 'diamond',
        symbolOffset: ['-132%', '-40%'],
        symbolSize: [18, 11],
        yAxisIndex: 0,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 1,
            y: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: 'rgba(129, 202, 254, 1)' },
              { offset: 1, color: 'rgba(59, 170, 250, 1)' },
            ],
          },
        },
        tooltip: {
          show: false,
        },
      },
      // 第一个柱状图的柱体（功率实际值）
      {
        z: 1,
        name: props.barName[0] ?? '',
        type: 'bar',
        barWidth: 16,
        barGap: '5%',
        data: props.dataBar1 ?? [],
        yAxisIndex: 0,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 1,
            y: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: 'rgba(20, 67, 133, 1)' },
              { offset: 0.5, color: 'rgba(59, 170, 250, 1)' },
              { offset: 0.5, color: 'rgba(16, 79, 149, 1)' },
              { offset: 1, color: 'rgba(23, 98, 182, 1)' },
            ],
          },
        },
      },
      // 第二个柱状图的钻石顶部（电机扭矩实际值）
      {
        z: 2,
        name: props.barName[1] ?? '',
        type: 'pictorialBar',
        symbolPosition: 'end',
        data: props.dataBar2 ?? [],
        symbol: 'diamond',
        symbolOffset: ['-42%', '-40%'],
        symbolSize: [18, 11],
        yAxisIndex: 0,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 1,
            y: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: 'rgba(149, 251, 244, 1)' },
              { offset: 1, color: 'rgba(62, 207, 247, 1)' },
            ],
          },
        },
        tooltip: {
          show: false,
        },
      },
      // 第二个柱状图的柱体（电机扭矩实际值）
      {
        z: 1,
        name: props.barName[1] ?? '',
        type: 'bar',
        barWidth: 16,
        data: props.dataBar2 ?? [],
        yAxisIndex: 0,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 1,
            y: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: 'rgba(28, 121, 153, 1)' },
              { offset: 0.5, color: 'rgba(69, 207, 216, 1)' },
              { offset: 0.5, color: 'rgba(37, 149, 180, 1)' },
              { offset: 1, color: 'rgba(18, 91, 111, 1)' },
            ],
          },
        },
      },
      // 第三个柱状图的钻石顶部（FGC）
      {
        z: 2,
        name: props.barName[2] ?? '',
        type: 'pictorialBar',
        symbolPosition: 'end',
        data: props.dataBar3 ?? [],
        symbol: 'diamond',
        symbolOffset: ['42%', '-40%'],
        symbolSize: [18, 11],
        yAxisIndex: 1,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 1,
            y: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: 'rgba(255, 140, 140, 1)' },
              { offset: 1, color: 'rgba(245, 108, 108, 1)' },
            ],
          },
        },
        tooltip: {
          show: false,
        },
      },
      // 第三个柱状图的柱体（FGC）
      {
        z: 1,
        name: props.barName[2] ?? '',
        type: 'bar',
        barWidth: 16,
        data: props.dataBar3 ?? [],
        yAxisIndex: 1,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 1,
            y: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: 'rgba(133, 67, 67, 1)' },
              { offset: 0.5, color: 'rgba(250, 108, 108, 1)' },
              { offset: 0.5, color: 'rgba(149, 79, 79, 1)' },
              { offset: 1, color: 'rgba(182, 98, 98, 1)' },
            ],
          },
        },
      },
      // 第四个柱状图的钻石顶部（AGC）
      {
        z: 2,
        name: props.barName[3] ?? '',
        type: 'pictorialBar',
        symbolPosition: 'end',
        data: props.dataBar4 ?? [],
        symbol: 'diamond',
        symbolOffset: ['140%', '-40%'],
        symbolSize: [18, 11],
        yAxisIndex: 1,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 1,
            y: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: 'rgba(100, 200, 255, 1)' },
              { offset: 1, color: 'rgba(32, 160, 255, 1)' },
            ],
          },
        },
        tooltip: {
          show: false,
        },
      },
      // 第四个柱状图的柱体（AGC）
      {
        z: 1,
        name: props.barName[3] ?? '',
        type: 'bar',
        barWidth: 16,
        data: props.dataBar4 ?? [],
        yAxisIndex: 1,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            x2: 1,
            y: 0,
            y2: 0,
            colorStops: [
              { offset: 0, color: 'rgba(67, 133, 180, 1)' },
              { offset: 0.5, color: 'rgba(108, 200, 250, 1)' },
              { offset: 0.5, color: 'rgba(79, 149, 200, 1)' },
              { offset: 1, color: 'rgba(98, 160, 220, 1)' },
            ],
          },
        },
      },
      {
        name: props.lineName[0] ?? '',
        type: 'line',
        data: props.dataLine1 ?? [],
        yAxisIndex: 1,
        symbol: 'circle',
        symbolSize: 4,
        itemStyle: {
          color: 'rgba(235, 163, 63, 1)',
        },
      },
      {
        name: props.lineName[1] ?? '',
        type: 'line',
        data: props.dataLine2 ?? [],
        yAxisIndex: 1,
        symbol: 'circle',
        symbolSize: 4,
        itemStyle: {
          color: '#91cc75',
        },
      },
    ],
  });

  const initCharts = () => {
    try {
      formatterOption();
      if (chartRef.value && !chartInstance) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance?.setOption(option.value, true);
      }
    } catch (error) {
      console.error('图表初始化失败:', error);
    }
  };

  const updateChart = () => {
    try {
      formatterOption();
      option.value.title.text = props.title;
      option.value.xAxis.data = Array.isArray(props.datax) ? props.datax : [];
      if (chartInstance) {
        chartInstance.setOption(option.value, true);
        handleResize();
      }
    } catch (error) {
      console.error('更新图表失败:', error);
    }
  };

  const formatterOption = () => {
    const series = [];
    const allSeries = option.value.series;
    
    // dataBar1 钻石顶部和柱体（索引0和1）
    if (allSeries[0]) {
      allSeries[0].data = Array.isArray(props.dataBar1) ? props.dataBar1 : [];
      series.push(allSeries[0]);
    }
    if (allSeries[1]) {
      allSeries[1].data = Array.isArray(props.dataBar1) ? props.dataBar1 : [];
      series.push(allSeries[1]);
    }
    
    // dataBar2 钻石顶部和柱体（索引2和3）
    if (props.dataBar2 && props.dataBar2.length > 0) {
      if (allSeries[2]) {
        allSeries[2].data = props.dataBar2;
        series.push(allSeries[2]);
      }
      if (allSeries[3]) {
        allSeries[3].data = props.dataBar2;
        series.push(allSeries[3]);
      }
    }
    
    // dataBar3 钻石顶部和柱体（索引4和5）
    if (props.dataBar3 && props.dataBar3.length > 0) {
      if (allSeries[4]) {
        allSeries[4].data = props.dataBar3;
        series.push(allSeries[4]);
      }
      if (allSeries[5]) {
        allSeries[5].data = props.dataBar3;
        series.push(allSeries[5]);
      }
    }
    
    // dataBar4 钻石顶部和柱体（索引6和7）
    if (props.dataBar4 && props.dataBar4.length > 0) {
      if (allSeries[6]) {
        allSeries[6].data = props.dataBar4;
        series.push(allSeries[6]);
      }
      if (allSeries[7]) {
        allSeries[7].data = props.dataBar4;
        series.push(allSeries[7]);
      }
    }
    
    // dataLine1（索引8）
    if (props.dataLine1 && props.dataLine1.length > 0) {
      if (allSeries[8]) {
        allSeries[8].data = props.dataLine1;
        series.push(allSeries[8]);
      }
    }
    
    // dataLine2（索引9）
    if (props.dataLine2 && props.dataLine2.length > 0) {
      if (allSeries[9]) {
        allSeries[9].data = props.dataLine2;
        series.push(allSeries[9]);
      }
    }
    
    option.value.series = series;
    option.value.yAxis[0].name = props.yAxisName[0];
    option.value.yAxis[1].name = props.yAxisName[1];
    option.value.legend.data = [...props.barName, ...props.lineName];
    option.value.title.text = props.title;
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      nextTick(() => {
        initCharts();
      });
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', updateChart);
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', updateChart);
    chartInstance?.dispose();
  });

  watch(
    () => [props.datax, props.dataBar1, props.dataBar2, props.dataBar3, props.dataBar4, props.dataLine1, props.dataLine2, props.title],
    () => updateChart(),
    { deep: true }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
  });

  // 窗口大小变化处理
  const handleResize = () => {
    nextTick(() => {
      chartInstance?.resize();
    });
  };
</script>
<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
